package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_message;
import com.wehealth.dm.DM_Messages;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Message extends Fragment {
	
	private static  String JSONResult;
	private List<DM_Messages> listData;
	private List<String> titlelistData;
	private ListView listView;
	private MainActivity context;


	public  Message()
	{
		Log.i("init:", "Message"); 
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.message, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		//SIMMON_ADD
		//读取接口数据
		new Thread(){
			@Override
			public void run(){
			//你要执行的方法
				try {
					InitMessageListData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			//执行完毕后给handler发送一个空消息
			handler.sendEmptyMessage(0);
			}
			}.start();

		
		MainActivity activity = (MainActivity)getActivity();
		MobclickAgent.openActivityDurationTrack(false);
		
		context = activity;
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_Message);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    context.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		 
	}

	
	//SIMMON_ADD
	
	private void  InitMessageListData() throws IOException
	{
		 String urlAPI = com.wehealth.util.GetUrl.Message_GetList();
		 HttpPost httpRequest= new HttpPost(urlAPI);
		 List <NameValuePair> params = new ArrayList <NameValuePair>(); 
		 //将来这个数据从其他界面传过来
		 String userID = "1";
		 params.add(new BasicNameValuePair("userID",userID));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);	 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
			 }
		 }
		 catch(Exception e)
		 {
			 Log.e("error:",  e.toString());		 
		 }

	}
	
	//定义Handler对象
		private Handler handler =new Handler(){

			@Override
			public void handleMessage(android.os.Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if(JSONResult!=null){
				    BindList(JSONResult);
				    JSONResult =null;
				}else{
				    //context.openMainActivityDialog(); 
				}
			}
			
		};
		

		
		//将JSON数据绑定到LISTVIEW
		private void BindList(String strJSON)
		{
			try 
			{  
			    try
			    {
				    JSONObject jsonObject = new JSONObject(strJSON);		    
				    JSONArray  aNews =  new JSONArray( jsonObject.getString("result") ); 
				    listData = new ArrayList<DM_Messages>();
				    titlelistData = new ArrayList<String>();
				    String title;
				    String message;
				    String state;
				    for(int i=0; i<aNews.length(); i++){
				    		title = aNews.getJSONObject(i).getString("title");
				    		titlelistData.add(title);
				    		message = aNews.getJSONObject(i).getString("message");
				    		state = aNews.getJSONObject(i).getString("state");
				    		DM_Messages  item = new DM_Messages(title, message,state);
				    		listData.add(item);
				    }
				    
				    MainActivity activity = (MainActivity)getActivity();		
				    listView = (ListView) activity.findViewById(R.id.message_list);
				    
				    Adapter_message adapter = new Adapter_message(context, listData);
				    
			        listView.setAdapter(adapter);
			        
			        //SIMMON_ADD begin
			        listView.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view,
								int pos, long pos2) {
							
							DM_Messages item = listData.get(pos);
							Message_content message_content = new Message_content(item);

							if (getActivity() instanceof MainActivity)
							{
								MainActivity activity = (MainActivity) getActivity();
								activity.switchContent(message_content);
							}
							
						}
					});
			        //SIMMON_ADD end
			    }
			    catch(JSONException ex)
			    {
			    		Log.e("JSON Error: ", ex.toString()); 
			    }
			} 
			catch (Exception ex) 
			{  
			    
				Log.e("error: ",  ex.toString());
			}
		}

	    @Override
	    public void onPause() {
	        // TODO Auto-generated method stub
	        super.onPause();
	        MobclickAgent.onPageEnd("Message"); 
	    }


	    @Override
	    public void onResume() {
	        // TODO Auto-generated method stub
	        super.onResume();
	        MobclickAgent.onPageStart("Message"); 
	    }

}
